import { Loading, Message, MessageBox } from 'element-ui'
import request from '@/utils/open/request'
import $com from '@/utils/open/common'

/**
 * element 自定义封装脚本方法，特针对模板生成组件
 */
export default {
  /**
   * 格式化字段
   */
  formatField(value, property, type) {
    if (property === 'status') {
      if (value.key === '1') {
        return '<i class="el-icon-check"></i>'
      } else if (value.key === '2') {
        return '<i class="el-icon-close"></i>'
      }
    }
    if (type === 'select' || type === 'radio') {
      return value.value
    }

    if (type === 'checkbox') {
      const array = []
      for (const k of value) {
        array.push(k.value)
      }
      return array.toString()
    }
    if (property.indexOf('Desc') !== -1) {
      return value.value
    }
    if (type === 'date') {
      return $com.format(value, 'YYYY-MM-DD HH:mm:ss')
    }
    return value
  },
  /**
   * 无权限提醒
   */
  noAuth() {
    this.errorMsg('无权限查看')
  },
  /**
   * 重置组件
   *
   * @param that
   * @param name
   */
  reset(that, name) {
    that.$refs[name].resetFields()
  },
  /**
   * 排序參數处理
   * 针对特对参数转化，实体字段和数据库字段，参考pdm
   *
   * @param that
   * @param column
   */
  order(that, column) {
    const dicField = ['text', 'number', 'type', 'desc', 'select', 'name', 'way', 'size', 'time', 'date', 'radio', 'color', 'tag', 'switch', 'slider', 'order']
    switch (column.order) {
      case 'ascending': that.page.direction = 'asc'; break
      case 'descending': that.page.direction = 'desc'; break
      default: that.page.direction = ''
    }
    const s = column.prop
    if (s != null && s.length > 0) {
      if (dicField.indexOf(s) > -1) {
        that.page.sort = s + '_'
        return
      }
      const array = []
      let m = ''
      for (let i = 0; i < s.length; i++) {
        const j = s.substring(i, i + 1)
        if (isCaps(j)) {
          array.push(m)
          m = ''
          m += j.toLocaleLowerCase()
        } else {
          m += j
          if (i === (s.length - 1)) {
            array.push(m)
          }
        }
      }
      that.page.sort = array.toString().replace(/,/g, '_')
    } else {
      that.page.sort = ''
    }
    function isCaps(text) {
      if (text < 'A' || text > 'Z') {
        return false
      } else {
        return true
      }
    }
  },
  orderDefault(that, column) {
    switch (column.order) {
      case 'ascending': that.page.direction = 'asc'; break
      case 'descending': that.page.direction = 'desc'; break
      default: that.page.direction = ''
    }
    const s = column.prop
    if (s != null && s.length > 0) {
      that.page.sort = s
    } else {
      that.page.sort = ''
    }
  },
  /**
   * 查询分页组件封装
   *
   * @param that
   * @param url
   * @param params
   * @param success
   */
  queryPage(that, url, params, success) {
    params['size'] = that.page.size
    params['number'] = that.page.number
    params['sort'] = that.page.sort
    params['direction'] = that.page.direction
    that.tableLoading = true
    request.get(url, params).then(res => {
      if (res) {
        if (res.code === 200) {
          success(res)
        } else {
          this.errorMsg(res.message)
        }
      }
      setTimeout(() => {
        that.tableLoading = false
      }, 500)
    }).catch(res => {
      that.tableLoading = false
    })
  },
  /**
   * 删除组件封装 组件对话框
   *
   * @param that
   * @param url
   * @param params
   * @param success
   */
  del(that, url, params, success) {
    this.delTitle(that, '此操作将删除该记录, 是否继续?', url, params, success)
  },
  /**
   *
   * @param that
   * @param title
   * @param url
   * @param params
   * @param success
   */
  delTitle(that, title, url, params, success) {
    this.confirm('提示', title, (instance, done) => {
      request.delete(url, params).then(res => {
        if (res) {
          if (res.code === 200) {
            setTimeout(() => {
              this.successMsg('操作成功!')
            }, 500)
            instance.confirmButtonLoading = false
            done()
            success()
          } else {
            setTimeout(() => {
              this.errorMsg('操作失败!')
            }, 500)
            instance.confirmButtonLoading = false
          }
        }
      }).catch(res => {
        done()
        instance.confirmButtonLoading = false
      })
    })
  },
  /**
   * PUT组件对话框
   * @param that
   * @param title
   * @param url
   * @param params
   * @param success
   */
  put(that, title, url, params, success) {
    this.confirm('提示', title, (instance, done) => {
      request.putForm(url, params).then(res => {
        if (res) {
          if (res.code === 200) {
            setTimeout(() => {
              this.successMsg('操作成功!')
            }, 500)
            instance.confirmButtonLoading = false
            done()
            success()
          } else {
            setTimeout(() => {
              this.errorMsg('操作失败!')
            }, 500)
            instance.confirmButtonLoading = false
          }
        }
      }).catch(res => {
        done()
        instance.confirmButtonLoading = false
      })
    })
  },
  /**
   * POST组件对话框
   * @param that
   * @param title
   * @param url
   * @param params
   * @param success
   */
  post(that, title, url, params, success) {
    this.confirm('提示', title, (instance, done) => {
      request.postForm(url, params).then(res => {
        if (res) {
          if (res.code === 200) {
            setTimeout(() => {
              this.successMsg('操作成功!')
            }, 500)
            instance.confirmButtonLoading = false
            done()
            success()
          } else {
            setTimeout(() => {
              this.errorMsg('操作失败!')
            }, 500)
            instance.confirmButtonLoading = false
          }
        }
      }).catch(res => {
        done()
        instance.confirmButtonLoading = false
      })
    })
  },
  /**
   * GET组件对话框
   * @param that
   * @param title
   * @param url
   * @param params
   * @param success
   */
  get(that, title, url, params, success) {
    this.confirm('提示', title, (instance, done) => {
      request.get(url, params).then(res => {
        if (res) {
          if (res.code === 200) {
            setTimeout(() => {
              this.successMsg('操作成功!')
            }, 500)
            instance.confirmButtonLoading = false
            done()
            success()
          } else {
            setTimeout(() => {
              this.errorMsg('操作失败!')
            }, 500)
            instance.confirmButtonLoading = false
          }
        }
      }).catch(res => {
        done()
        instance.confirmButtonLoading = false
      })
    })
  },
  /**
   * 成功提醒
   * @param msg
   */
  successMsg(msg) {
    Message({
      showClose: true,
      message: msg,
      type: 'success',
      duration: 5 * 1000
    })
  },
  /**
   * 警告提醒
   *
   * @param msg
   */
  warnMsg(msg) {
    Message({
      showClose: true,
      message: msg,
      type: 'warning',
      duration: 5 * 1000
    })
  },
  /**
   * 操作框提醒
   *
   * @param config
   * @param {Function} confirmFn 确认回调
   * @param {Function} cancelFN 取消回调
   */
  confirm(config, confirmFn, cancelFN) {
    const option = {
      title: '提示',
      message: '确定执行该操作吗?',
      confirmButtonText: '确定',
      cancelButtonText: '取消'
    }
    if (config) {
      for (const key in option) {
        if (key && config.hasOwnProperty(key)) {
          option[key] = config[key]
        }
      }
    }

    // debugger
    var conObj = {}
    MessageBox.confirm(option.message, option.title, {
      confirmButtonText: option.confirmButtonText,
      cancelButtonText: option.cancelButtonText,
      beforeClose: (action, instance, done) => {
        conObj = instance
        // debugger
        if (action === 'confirm') { // 确认
          instance.confirmButtonLoading = true
          instance.confirmButtonText = '操作中...'
          if (confirmFn && typeof confirmFn === 'function') {
            confirmFn(instance, done)
          } else {
            done()
          }
        } else { // 取消
          if (cancelFN && typeof cancelFN === 'function') {
            cancelFN(instance, done)
          } else {
            done()
          }
        }
      }
    }).then(res => {
      // var t = arguments
      // debugger
      conObj.confirmButtonLoading = false
      conObj.confirmButtonText = option.confirmButtonText
    }).catch(res => {
      // debugger
      conObj.confirmButtonLoading = false
      conObj.confirmButtonText = option.confirmButtonText
    })

    // MessageBox({
    //   title: title,
    //   message: message,
    //   confirmButtonText: '确定2',
    //   cancelButtonText: '取消1',
    //   showCancelButton: true,
    //   confirmButtonClass: 'el-button el-button--danger',
    //   type: 'warning',
    //   beforeClose: (action, instance, done) => {
    //     // instance = instance
    //     // debugger
    // if (action === 'confirm') {
    //   instance.confirmButtonLoading = true
    //   instance.confirmButtonText = '操作中...'
    //   confirm(instance, done)
    // } else {
    //   done()
    // }
    //   }
    // }).then(() => {
    //   // debugger
    //   // instance.confirmButtonLoading = true
    //   // instance.confirmButtonText = '操作中...'
    // }).catch(() => {

    //   // debugger
    // })
  },
  /**
* 错误提醒
*
* @param msg
*/
  errorMsg(msg) {
    Message({
      message: msg,
      type: 'error',
      duration: 5 * 1000,
      showClose: true
    })
  },
  startLoading() {
    const loading = Loading.service({})
  },
  endLoading() {
    const loading = Loading.service({})
    setTimeout(() => {
      loading.close()
    }, 500)
  }
}
